package rsschart;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rsschart.charter.BarChart;
import rsschart.charter.Charter;
import rsschart.charter.LineChart;
import rsschart.feed.Category;
import rsschart.feed.DataSet;
import rsschart.feed.RssChart;

public class BuildChart extends HttpServlet {

	protected void service(HttpServletRequest request, 
						   HttpServletResponse response) throws ServletException, IOException {
		
		String chartTitle;
		String dataSetsName;
		String dataSetsValueLabel;
		String dataSetName;
		String dataSetVals;
		String catgName;
		String catgVals;
		int setCount;
		int pointCount;
		String chartType;
		//-- in pixels:
		int chartWidth;
		int chartHeight;
		
		chartType = request.getParameter("chartType");
		
		DataSet dataSet;
		
		chartTitle = request.getParameter("chartTitle");
		setCount = Integer.parseInt(request.getParameter("setCount"));
		pointCount = Integer.parseInt(request.getParameter("pointCount"));
		
		catgName = request.getParameter("catgName");
		catgVals = request.getParameter("catgVals");
		dataSetsName = request.getParameter("dataSetsName");
		dataSetsValueLabel = request.getParameter("dataSetsValueLabel");
		
		chartWidth = Integer.parseInt(request.getParameter("chartWidth"));
		chartHeight = (3*chartWidth)/4;

		RssChart rss = new RssChart();
		Category catg = new Category();
		rss.setDataSetsName(dataSetsName);
		rss.setDataSetsValueLabel(dataSetsValueLabel);

		String inputName;
		
		//-- set the properties for each dataSet on the submitted page:
		for(int i=0;i<setCount;i++) {
			dataSet = new DataSet();
			inputName = "dataSetName" + (i+1);
			dataSetName = request.getParameter(inputName);
			dataSet.setName(dataSetName);
			inputName = "dataSetVals" + (i+1);
			dataSetVals = request.getParameter(inputName);
			dataSet.setValueString(dataSetVals);
			rss.addDataSet(dataSet);
		}
		//-- other singular properties
		rss.setWidth(chartWidth);
		rss.setHeight(chartHeight);

		rss.setTitle(chartTitle);
		
		//catg.setId(...); // not used in demo
		catg.setName(catgName);
		catg.setValueString(catgVals);
		rss.setCategory(catg);

		Charter chart;
		
		if (chartType.equalsIgnoreCase("bar")) {
			chart = new BarChart();
		}
		else if (chartType.equalsIgnoreCase("line")) {
			chart = new LineChart();
		}
		else {
			chart = new BarChart();
		}
				
		String content;
		content = chart.draw(rss);

		//-- set the content type appropriately:
		response.setContentType("image/svg+xml");
		
		PrintWriter writer;
		writer = response.getWriter();
		writer.write(content);
		writer.flush();
		writer.close();
	
	}

}
